<template>
  <el-table :data="foodStore.foodRecipeDialog.data.stepList"
            border class="food-step-table">
    <el-table-column type="index" align="center" width="90">
      <template #header>
        <el-button type="primary" @click="handleAddClick">新增</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="content" label="内容" align="center" min-width="20%" />
    <el-table-column prop="imageUrl" label="图片" align="center" min-width="20%">
      <template #default="scope">
        <el-image v-if="scope.row.imageUrl" :src="serviceFileRootPath + scope.row.imageUrl" />
      </template>
    </el-table-column>

    <el-table-column label="操作" align="center" width="100">
      <template #default="scope">
        <el-button type="primary" text
                   @click="handleEditClick(scope.$index, scope.row)">编辑</el-button>
        <el-button type="danger" text
                   @click="handleDeleteClick(scope.$index)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { useFoodStore } from '@/store/food.ts'
import { IFoodStep } from '@/types/food.ts'
import { deepCopyObject } from 'vue3-common/utils/dataUtil'
import { commonElMessageBox } from 'vue3-common/utils/elUtil'
import { serviceFileRootPath } from '@/utils'

const foodStore = useFoodStore()

const handleAddClick = () => {
  foodStore.foodStepApiType = 'ADD'
  foodStore.foodStepImageList = []
  foodStore.foodStepDialog = {
    title: '新增步骤',
    visible: true,
    data: foodStore.getEmptyFoodStep()
  }
}

const handleEditClick = (index: number, step: IFoodStep) => {
  foodStore.editFoodStepIndex = index
  foodStore.foodStepApiType = 'UPDATE'
  foodStore.foodStepDialog = {
    title: '编辑步骤',
    visible: true,
    data: deepCopyObject(step)
  }
}

const handleDeleteClick = (index: number) => {
  commonElMessageBox('确认删除该步骤?').then(() => {
    foodStore.foodStepApiType = 'DELETE'
    foodStore.foodRecipeDialog.data.stepList.splice(index, 1)
    foodStore.foodRecipeDialog.data.stepList.forEach((item) => {
      if (item.sort > index) {
        item.sort -= 1
      }
    })
  })
}
</script>

<style lang="scss">
.food-step-table {
  .el-image {
    width: 100%;
    height: 100%;

    max-height: 200px;
    max-width: 200px;
  }
}
</style>
